import { ref } from "vue";
import { defineStore } from "pinia";
import {
  getGalList_API,
  getGalTagList_API,
  getGalListOfSelect_API,
} from "@/axios/api/gal.js";

export const useGalStores = defineStore("sy-galgame", () => {
  const galData = ref([]); //查询的Gal列表
  const galTagData = ref({}); //Gal的Tag列表
  const galTagSelectData = ref([]); //GalTag的检索列表

  //获取gal列表
  const getGalListAction = (isFirst = false) => {
    return new Promise((rel, rea) => {
      if (isFirst) {
        getGalJsonAction()
          .then((res) => {
            rel(galData.value);
          })
          .catch((res) => {
            rea(res);
          });
      } else {
        rel(galData.value);
      }
    });
  };

  //获取galTag列表
  const getGalTagListAction = () => {
    const data = galTagData.value;
    return new Promise((rel, rea) => {
      if (Object.keys(data).length > 0) {
        rel(data);
      } else {
        getGalTagList_API()
          .then((res) => {
            galTagData.value = res.data.result;
            rel(galTagData.value);
          })
          .catch((res) => {
            rea(res);
          });
      }
    });
  };

  //获取选择的GalTag
  const getTagSelectDataAction = () => {
    return JSON.parse(JSON.stringify(galTagSelectData.value));
  };

  //获取检索指定的Gal
  const getGalListOfSelectAction = (tagData, text) => {
    galTagSelectData.value = JSON.parse(JSON.stringify(tagData));
    let tagId = "";
    for (let i = 0; i < tagData.length; i++) {
      if (i != 0) {
        tagId += ",";
      }
      tagId += tagData[i].id;
    }
    return new Promise((rel, rea) => {
      getGalListOfSelect_API({ tagId: tagId, text: text })
        .then((res) => {
          galData.value = res.data.result;
          //更新了源
          //   isDataOfWhereF5.value = true;
          rel(res);
        })
        .catch((res) => {
          console.log(res);
          rea(res);
        });
    });
  };

  //获取Tag从下标
  const getGalTagListOfIndexAction = (indexs) => {
    const arr = galData.value;
    let cur = [];
    if (arr.length != 0) {
      for (let i = 0; i < indexs.length; i++) {
        const element = indexs[i];
        //查询当前社团
        const curTag = galTagData.value.find((u) => u.id == element).title;
        const arr = galData.value.filter((u) => u.club == curTag);
        cur = cur.concat(arr);
      }
    }
    return cur;
  };

  const getGalJsonAction = () => {
    galTagSelectData.value = [];
    return new Promise((rel, rea) => {
      getGalList_API()
        .then((res) => {
          galData.value = res.data;
          rel(res.data);
        })
        .catch((res) => {
          rea("请求gal数据失败");
        });
    });
  };

  return {
    getGalJsonAction,
    getGalListAction,
    getGalListOfSelectAction,
    getGalTagListAction,
    getGalTagListOfIndexAction,
    getTagSelectDataAction,
  };
});
